//index.js
//获取应用实例
const app = getApp();
const util = require('../../utils/util.js');
const config=require('../../utils/config.js');
var that;
Page({
  data: {
    userInfo: [],
    ready: false,
    classList: [],
    colorList: ['#9C27B0', '#673AB7', '#3F51B5', '#00BCD4', '#009688', '#CDDC39', '#FFC107', '#FF5722', '#8BC34A','#FF9800']
  },
  list: function (e) {
    // console.log('list',e)
    let class_id = e.currentTarget.dataset.id;
    let class_name= e.currentTarget.dataset.name;
    wx.navigateTo({
      url: '/pages/itemlist/itemlist?class_id=' + class_id + '&class_name=' + class_name,
    })
  },
  mine: function () {
    wx.navigateTo({
      url: '/pages/mine/mine',
    })
  },
  click: function () {
    wx.navigateTo({
      url: '/pages/scan/scan',
    })
  },
  onLoad: function () {
    that = this
    initView();
    wx.login({
      success: function (res) {
        console.log(res.code)
        if (res.code) {
          let url = '/app/on_login';
          let data = {
            code: res.code
          }
          util.request(url, data, res => {
            wx.hideLoading()
            // console.log(url, res)
            var openid = res.open_id
            wx.setStorageSync('open_id', openid);
            if (res.ret == 2) {
              wx.redirectTo({
                url: '/pages/bind/bind',
              })
            } else {
              that.setData({
                ready: true
              })
            }
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    });
    
    
    // wx.connectSocket({
    //   url: getApp().globalData.wsserver+'/ws?user_id=' + getApp().globalData.userid
    // })
    /*wx.onSocketOpen(function (res) {
      //console.log('WebSocket连接已打开！')
      wx.sendSocketMessage({
        data:JSON.stringify({user_id:'11111', cmd: 'ok;' })
      })
    })*/

    wx.onSocketMessage(function (res) {
      var rt = JSON.parse(res.data)
      console.log(JSON.stringify(rt))
      console.log('收到服务器内容：' + rt.toid)

      if (rt.cmd == 'refuse') {
        that.openAlert("对方拒绝你借物品")
      } else if (rt.cmd == 'ok') {
        wx.request({
          url: getApp().globalData.serverip + '/borrow?openid=' + getApp().globalData.userid + '&itemid=' + rt.itemid,
          method: 'POST',
          header: {
            'content-type': 'application/json', // 默认值
            'sessionid': wx.getStorageSync("sessionid")
          },
          success: function (res) {
            that.openAlert("对方同意，并已借到物品")
            wx.hideLoading()
            console.log(JSON.stringify(res))
          }
        })

      }

    })
    /*var socketOpen = false
    var socketMsgQueue = []
    wx.connectSocket({
      url: 'ws://192.168.10.195/ws?user_id=11111'
    })
    wx.onSocketOpen(function (res) {
      socketOpen = true
      for (var i = 0; i < socketMsgQueue.length; i++) {
        sendSocketMessage(socketMsgQueue[i])
      }
      socketMsgQueue = []
    })
    function sendSocketMessage(msg) {
      if (socketOpen) {
        wx.sendSocketMessage({
          data: msg
        })
      } else {
        socketMsgQueue.push(msg)
      }
    }*/
    /***** */
    //console.log(wx.getStorageSync("sessionid"))
    var test = app.globalData.userid;
    console.log(test)
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      /*wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
          console.log(JSON.stringify(this.data.userInfo))
          if (this.data.userInfo.nickName!=null){
            console.log(app.globalData.userid)
            
          }
        }
      })*/
    }

  },
})

function initView(){
  let url = '/app/class_list';
  let data = {};
  util.request(url, data, res => {
    console.log(url, res)
    that.setData({
      classList: res.rows,
    })
    wx.setStorage({
      key: 'class_list',
      data: res.rows,
    })
  })
}